<template>
	<view class="statistics">
		<view class="header"><u-tabs :list="list" :is-scroll="false" :current="tabCur" @change="tabSelect"></u-tabs></view>

		<u-cell-group>
			<u-cell-item title="日期" :arrow="false">
				<picker slot="right-icon" mode="date" :value="date" fields="month" @change="dateChange">
					<view class="picker">{{ date }}</view>
				</picker>
			</u-cell-item>
		</u-cell-group>

		<!-- 月支出统计:利用v-show，防止用v-if删除div导致饼状图对象失效 -->
		<view v-show="tabCur == 0">
			<u-cell-item icon="calendar" style="color: rgb(0, 129, 255);" :title="'月统计情况:总支出:' + monthOutSum + '元'" :arrow="false"></u-cell-item>

			<view class="duiwei-charts"><canvas canvas-id="monthOutPie" id="monthOutPie" class="charts" @touchstart="touchPie"></canvas></view>

			<!-- 当月支出折线图 -->
			<view class="duiwei-charts"><canvas canvas-id="monthOutLine" id="monthOutLine" class="charts" @touchstart="touchLine"></canvas></view>
		</view>

		<!-- 月收入统计 -->
		<view v-show="tabCur == 1">
			<u-cell-item icon="calendar" style="color: rgb(0, 129, 255);" :title="'月统计情况:总收入:' + monthInSum + '元'" :arrow="false"></u-cell-item>

			<view class="duiwei-charts"><canvas canvas-id="monthInPie" id="monthInPie" class="charts" @touchstart="touchPie"></canvas></view>
		</view>
	</view>
</template>

<script>
import uCharts from '@/components/u-charts/u-charts.min.js';

import { money_query } from '@/api/api.js';

export default {
	data() {
		return {
			Pie: {
				monthOutPie: null, // 月支出统计
				monthInPie: null // 月收入统计
			},
			Line: {
				monthOutLine: null // 月支出统计
			},
			list: [
				{
					name: '支出'
				},
				{
					name: '收入'
				}
			],
			cWidth: 750,
			cHeight: 500,
			monthOutSum: 0, // 月总支出
			monthInSum: 0, // 月总收入
			date: '',
			tabCur: 0,
			inMark: 'income',
			outMark: 'expenditure'
		};
	},
	onLoad() {
		this.date = this.$utils.dateFormat('YYYY-mm', new Date());

		// 设置真实px尺寸
		this.cWidth = uni.upx2px(this.cWidth);
		this.cHeight = uni.upx2px(this.cHeight);
	},
	onShow() {
		this.getServerData();
	},
	methods: {
		getServerData() {
			uni.showLoading({
				title: '加载中...',
				mask: true
			});
			
			// 拿到当前年月
			let yms = this.date.split('-');
			let endDay = new Date(yms[0], yms[1], 0).getDate(); // 本月最后一天

			// 月支出统计
			money_query({
				mark: this.outMark,
				startDate: this.date + '-01 00:00:00',
				endDate: this.date + '-' + endDay + ' 23:59:59'
			}).then(res => {
				uni.hideLoading();
				// 月支出总值
				this.monthOutSum = res.total;

				// 获得饼状图
				let series = this.changeMonthPie(res.list);
				this.showPie('monthOutPie', series);

				// 获得折线图
				let chartData = this.changeMonthLine(res.list);
				this.showLine('monthOutLine', chartData);
			});

			// 月收入统计
			money_query({
				mark: this.inMark,
				startDate: this.date + '-01 00:00:00',
				endDate: this.date + '-' + endDay + ' 23:59:59'
			}).then(res => {
				let series = this.changeMonthPie(res.list);
				this.monthInSum = res.total;
				this.showPie('monthInPie', series);
			});
		},
		// 数据转变饼状图数据格式
		changeMonthPie(changeData) {
			let series = [];
			let typeMap = {}; // 存每个分类金额
			// 得出每个分类金额总数
			changeData.forEach(data => {
				let type = data.type;
				let money = new Number(data.money);

				if (typeMap[type]) {
					typeMap[type] += money * 100;
				} else {
					typeMap[type] = money * 100;
				}
			});
			for (let key in typeMap) {
				let serie = {
					name: key + ':' + typeMap[key] / 100,
					data: typeMap[key] / 100
				};
				series.push(serie);
			}
			return series;
		},
		// 获得饼状图对象保存起来
		showPie(canvasId, series) {
			this.Pie[canvasId] = new uCharts({
				$this: this,
				canvasId: canvasId,
				type: 'pie',
				fontSize: 11,
				padding: [15, 15, 0, 15],
				legend: {
					show: true,
					lineHeight: 16,
					position: 'left',
					fontSize: 10
				},
				background: '#FFFFFF',
				pixelRatio: 1,
				series: series,
				animation: true,
				width: this.cWidth,
				height: this.cHeight,
				dataLabel: true,
				extra: {
					pie: {
						border: true,
						borderColor: '#FFFFFF',
						borderWidth: 3
					}
				}
			});
		},
		touchPie(e) {
			let canvasId = e.currentTarget.id;
			let curPie = this.Pie[canvasId];
			curPie.showToolTip(e, {
				format: function(item) {
					return item.name;
				}
			});
			curPie.touchLegend(e, {
				animation: true
			});

			// 通过点击图例找到数据下标，点击其他返回-1
			let legendIndex = curPie.getLegendDataIndex(e);
			if (legendIndex !== -1) {
				// 通过判断图例当前的show变量得知是否显示
				let curData = curPie.opts.series[legendIndex];
				if (curData.show) {
					this.monthOutSum = (this.monthOutSum * 1000 + curData.data * 1000) / 1000;
				} else {
					this.monthOutSum = (this.monthOutSum * 1000 - curData.data * 1000) / 1000;
				}
			}
		},
		// 数据转变折线图数据格式
		changeMonthLine(changeData) {
			let typeMap = {}; // 存每天总金额
			// 得出每个分类金额总数
			changeData.forEach(data => {
				let day = data.date.split(' ')[0];
				let money = data.money;

				if (typeMap[day]) {
					typeMap[day] += money * 100;
				} else {
					typeMap[day] = money * 100;
				}
			});

			let categories = [];
			let series = [];
			for (let key in typeMap) {
				categories.push(parseInt(key.split('-')[2]));
				series.push(typeMap[key] / 100);
			}

			return {
				categories: categories,
				series: [
					{
						name: '当日消费',
						data: series
					}
				]
			};
		},
		// 获得折线图对象保存起来
		showLine(canvasId, chartData) {
			this.Line[canvasId] = new uCharts({
				$this: this,
				canvasId: canvasId,
				type: 'line',
				fontSize: 11,
				dataLabel: false,
				dataPointShape: false,
				background: '#FFFFFF',
				pixelRatio: 1,
				categories: chartData.categories,
				series: chartData.series,
				animation: true,
				enableScroll: true,
				xAxis: {
					disabled: true,
					disableGrid: false,
					gridType: 'dash',
					gridEval: 5,
					itemCount: 31
				},
				yAxis: {
					disabled: true,
					disableGrid: true,
					format: val => {
						return val.toFixed(0);
					}
				},
				legend: {
					show: false
				},
				width: this.cWidth,
				height: this.cHeight
			});
		},
		touchLine(e) {
			let canvasId = e.currentTarget.id;
			this.Line[canvasId].showToolTip(e, {
				format: function(item, category) {
					return category + ':' + item.name + ':' + item.data;
				}
			});
		},
		dateChange(event) {
			this.date = event.detail.value;
			this.getServerData();
		},
		tabSelect(index) {
			this.tabCur = index;
		}
	}
};
</script>

<style lang="scss" scoped>
.statistics {
	background-color: #fff;
	.header {
		padding: 0 50rpx;
	}

	/*样式的width和height一定要与定义的cWidth和cHeight相对应*/
	.duiwei-charts {
		width: 750rpx;
		height: 500rpx;
		background-color: #ffffff;
		.charts {
			width: 750rpx;
			height: 500rpx;
			background-color: #ffffff;
		}
	}
}
</style>
